package myPackage.participant.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import myPackage.participant.domain.History;
import myPackage.participant.domain.Parent;
import myPackage.participant.domain.Student;
import myPackage.participant.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping("/calculate")
public class ParticipateController {
    @Autowired
    private UserService userService;
    /*
    CreditCard.get({id: 11})            GET     /user/123/card/11
    CreditCard.save({}, ccard)          POST    /user/123/card with post data “ccard”
    CreditCard.save({id: 11}, ccard)    POST    /user/123/card/11 with post data “ccard”
    CreditCard.query()                  GET     /user/123/card
    CreditCard.remove({id: 11})         DELETE  /user/123/card/11
    CreditCard.delete({id: 11})         DELETE  /user/123/card/11
        */

        //前端相应方法 http post
    @RequestMapping(method=RequestMethod.POST, value="/login")
    public @ResponseBody Object login(HttpServletRequest request,
                                      HttpServletResponse response,@RequestBody String body) {
        List informationUploaded = (new Gson()).fromJson(body, List.class);
        String usernameUploaded = (String)informationUploaded.get(0);
        Student queryStudent =  userService.getStudentDao().getStudentByUsername(usernameUploaded);
        Parent queryParent =  userService.getParentDao().getParentByUsername(usernameUploaded);
        Object resultObject = null;
        if(queryStudent == null&queryParent==null){
            resultObject = new Object[]{"failure",null,"用户名尚未注册"};
        }
        else if(queryStudent !=null){
            if(queryStudent.getPassword().equals((String)informationUploaded.get(1))){
                resultObject = new Object[]{"success","student","登录成功"};
            }
            else{
                resultObject = new Object[]{"failure",null,"密码错误"};
            }
        }
        else if(queryParent !=null){
            if(queryParent.getPassword().equals((String)informationUploaded.get(1))){
                resultObject = new Object[]{"success","parent","登录成功"};
            }
            else{
                resultObject = new Object[]{"failure",null,"密码错误"};
            }
        }
        return  resultObject;
    }

  @RequestMapping(method=RequestMethod.POST, value="/register")
  public @ResponseBody Object register(HttpServletRequest request,
                                       HttpServletResponse response,@RequestBody String body){
      List informationUploaded = (new Gson()).fromJson(body, List.class);
      String registerType = (String)informationUploaded.get(1);
     // Object resultObject = null;
      if(registerType.equals("student")){
          Student registerStudent =  (new Gson()).fromJson(informationUploaded.get(0).toString(), Student.class);
          if(userService.getStudentDao().getStudentByUsername(registerStudent.getUsername()) != null){
              return  new Object[]{"failure",null,"用户名重复"};
          }
          userService.getStudentDao().insert(registerStudent);
      }else{
          Parent registerParent =  (new Gson()).fromJson(informationUploaded.get(0).toString(), Parent.class);
          if(userService.getStudentDao().getStudentByUsername(registerParent.getUsername()) != null){
              return  new Object[]{"failure",null,"用户名重复"};
          }
          userService.getParentDao().insert(registerParent);
      }
      return  new Object[]{"success",null,"用户注册成功"};
  }
    /*

  @RequestMapping(method=RequestMethod.GET, value="/participant")     //query
  public @ResponseBody List<Participant> listAllParticipants(HttpServletRequest request, HttpServletResponse response) {
      List<Participant> queryResult = userService.listAllParticipants();
      //System.out.println("size " + queryResult.size() + "    request finished");
      return queryResult;
  }

  @RequestMapping(method=RequestMethod.POST, value="/participant")       //post
  public @ResponseBody Object newParticipantInformation(HttpServletRequest request,
                 HttpServletResponse response,@RequestBody String body) {
      Participant informationUploaded = (new Gson()).fromJson(body, Participant.class);
      userService.insertNewParticipant(informationUploaded);
      return new Object[]{"insert new Information finished"};
  }

  @RequestMapping(method=RequestMethod.POST, value="/participant/{username}")    //save
  //edit leave request
  public @ResponseBody String editInformation(HttpServletRequest request, HttpServletResponse response,
                            @PathVariable("username")String username,@RequestBody String body) {
      Participant informationUploaded = (new Gson()).fromJson(body, Participant.class);
      userService.updateInformation(informationUploaded);
      return "信息修改完成";
  }     */
    @RequestMapping(method=RequestMethod.POST, value="/exercise")
    public @ResponseBody Object exercise(HttpServletRequest request,
                                      HttpServletResponse response,@RequestBody String body) {
        List informationUploaded = (new Gson()).fromJson(body, List.class);
        List exerciseResult =(List)informationUploaded.get(1);
        Student student = userService.getStudentDao().getStudentByUsername((String)(informationUploaded.get(0)));
        History newHistory = new History();
        newHistory.setHistoryValue(((Double)(((List)exerciseResult.get(0)).get(0))).intValue(),((Double)(((List)exerciseResult.get(1)).get(0))).intValue(),((Double)(((List)exerciseResult.get(2)).get(0))).intValue(),((Double)(((List)exerciseResult.get(3)).get(0))).intValue(),((Double)(((List)exerciseResult.get(0)).get(1))).intValue(),((Double)(((List)exerciseResult.get(1)).get(1))).intValue(),((Double)(((List)exerciseResult.get(2)).get(1))).intValue(),((Double)(((List)exerciseResult.get(3)).get(1))).intValue());
        newHistory.setTotal(((Double)(((List)exerciseResult.get(0)).get(0))).intValue()+((Double)(((List)exerciseResult.get(1)).get(0))).intValue()+((Double)(((List)exerciseResult.get(2)).get(0))).intValue()+((Double)(((List)exerciseResult.get(3)).get(0))).intValue());
        String currentTime = new SimpleDateFormat("yy-MM-dd").format(new Date());
        newHistory.setDate(currentTime);
        newHistory.setStudent(student.getId());
        student.getHistories().add(newHistory);
       // userService.getHistoryDao().insert(newHistory);
        userService.getStudentDao().update(student);
        return "nothing";
    }
  @RequestMapping(method=RequestMethod.GET, value="/student/{username}")      //get
  public @ResponseBody
  Student getStudentInformation(HttpServletRequest request, HttpServletResponse response,
                                   @PathVariable("username")String username)
  {
      return userService.getStudentDao().getStudentByUsername(username);
  }
    @RequestMapping(method=RequestMethod.GET, value="/parent/{username}")      //get
    public @ResponseBody
    Parent getParentInformation(HttpServletRequest request, HttpServletResponse response,
                                  @PathVariable("username")String username)
    {
        return userService.getParentDao().getParentByUsername(username);
    }
    @RequestMapping(method=RequestMethod.POST, value="/exercise2")
    public @ResponseBody Object exercise2(HttpServletRequest request,
                                         HttpServletResponse response,@RequestBody String body) {
        List informationUploaded = (new Gson()).fromJson(body, List.class);
        List exerciseResult =(List)informationUploaded.get(1);
        Student student = userService.getStudentDao().getStudentByUsername((String)(informationUploaded.get(0)));
        History newHistory = new History();
        newHistory.setTotal(((Double)(((List)(informationUploaded.get(1))).get(0))).intValue());
        newHistory.setHybrid(((Double)(((List)(informationUploaded.get(1))).get(0))).intValue());
        newHistory.setHybrid_correct(((Double)(((List)(informationUploaded.get(1))).get(1))).intValue());
        String currentTime = new SimpleDateFormat("yy-MM-dd").format(new Date());
        newHistory.setDate(currentTime);
        newHistory.setStudent(student.getId());
        student.getHistories().add(newHistory);
        userService.getStudentDao().update(student);
        return "nothing";
    }
    @RequestMapping(method=RequestMethod.POST, value="/newChild")
    public @ResponseBody Object newChild(HttpServletRequest request,
                                      HttpServletResponse response,@RequestBody String body) {
        List informationUploaded = (new Gson()).fromJson(body, List.class);
        String usernameUploaded = (String)informationUploaded.get(0);
        String childNameUploaded = (String)informationUploaded.get(1);
        Student queryStudent =  userService.getStudentDao().getStudentByUsername(childNameUploaded);
        Parent queryParent =  userService.getParentDao().getParentByUsername(usernameUploaded);
        Object resultObject = null;
        if(queryStudent == null){
            resultObject = new Object[]{"wrong child name"};
        }
        else{
            queryStudent.setParent(queryParent.getId());
            userService.getStudentDao().update(queryStudent);
        }

        return  resultObject;
    }
}
